package com.yanqu.road.server.cmd.union.cross;

import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.ePlayerAttrType;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.twins.TwinsModule;
import com.yanqu.road.server.gameplayer.module.player.AttributeModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;

import java.math.BigInteger;

@Cmd(code = Protocol.S_UNION_CREATE_FROM_CROSS, desc = "创建联盟")
public class CreateUnionCmdFromCross extends AbstractCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {

        CrossUnionProto.UnionCreateCrossRespMsg crossRespMsg = CrossUnionProto.UnionCreateCrossRespMsg.parseFrom(packet.getBytes());

        AttributeModule attributeModule = player.getModule(AttributeModule.class);
        int freeCreateUnionTimes = (int) attributeModule.getAttribute(ePlayerAttrType.FreeCreateUnionTimes);
        if (player.getUserInfo().getVipExp() <= 0 || freeCreateUnionTimes >= GameConfig.UNION_FREE_CREATE_TIMES) {//没有充值的或者大于免费创建次数就需要消耗元宝
            player.getModule(CurrencyModule.class).removeCurrency(new Property(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(GameConfig.UNION_CREATE_INGOTS_COST)),
                    eLogMoneyType.Union, eLogMoneyType.UnionCreate);
        } else {
            attributeModule.addAttribute(ePlayerAttrType.FreeCreateUnionTimes, 1);   //增加免费创建商会次数
        }

        player.getUserInfo().setUnionUid(crossRespMsg.getUnionUid());
        player.notifyListener(eGamePlayerEventType.JoinUnionActivityCondition.getValue(),player.getUserInfo());  //玩家在线才更新
        if(crossRespMsg.getFirstCreate()){
            CrossUnionMgr.sendFirstJoinReward(player.getUserInfo());
        }
        //绝代改版商会活动得主动生成下数据 免得进不去
        player.getModule(TwinsModule.class).initSystem();

        player.sendPacket(Protocol.U_UNION_CREATE, UnionProto.UnionCreateRespMsg.newBuilder().setRet(0));
        UserMgr.addNeedUpdateToCrossMap(player.getUserId(), player.getUserInfo());
    }

    @Override
    public void sendData(GamePlayer player) {

    }
}
